import React, { PureComponent, Fragment } from "react";
import { connect } from "dva";
import { formatMessage, FormattedMessage } from "umi/locale";
import moment from "moment";
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Badge,
  Divider,
  Steps,
  Radio,
  Table
} from "antd";
import styles from "@/pages/List/TableList.less";

const FormItem = Form.Item;
const { Option } = Select;

const statusMap = ['success', 'default'];
const status = ["正常", "停用"];

/**
 * 新建表单
 */
const CreateForm = Form.create()(props => {
  const { modalVisible, form, handleCreate, handleModalVisible,roleData } = props;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      handleCreate(fieldsValue);
    });
  };
  return (
    <Modal
      destroyOnClose
      style={{ top: 64 }}
      width={600}
      title="新建员工"
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible()}
    >
      <FormItem
        labelCol={{ span: 5 }}
        wrapperCol={{ span: 15 }}
        label="手机号码"
      >
        {form.getFieldDecorator("username", {
          rules: [{ required: true, message: "请输入11位手机号码", len: 11 }]
        })(<Input placeholder="请输入" />)}
      </FormItem>
      <FormItem
        labelCol={{ span: 5 }}
        wrapperCol={{ span: 15 }}
        label="员工姓名"
      >
        {form.getFieldDecorator("nickname", {
          rules: [
            { required: true, message: "请输入2-20个字的姓名", min: 2, max: 20 }
          ]
        })(<Input placeholder="请输入" />)}
      </FormItem>
      <FormItem
        labelCol={{ span: 5 }}
        wrapperCol={{ span: 15 }}
        label="角色"
      >
        {form.getFieldDecorator("roleId")(
                <Select placeholder="请选择" style={{ width: "100%" }}>
                  {roleData.map(role => (
                    <Option key={role.id}>{role.roleName}</Option>
                  ))}
                </Select>
              )}
      </FormItem>
    </Modal>
  );
});

/**
 * 修改表单
 */
const UpdateForm = Form.create()(props => {
  const { updateModalVisible, form,values, handleUpdate, handleUpdateModalVisible,roleData } = props;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      //设置编辑ID
      fieldsValue.id = values.id;
      handleUpdate(fieldsValue);
    });
  };
  return (
    <Modal
      destroyOnClose
      style={{ top: 64 }}
      width={600}
      title="编辑员工"
      visible={updateModalVisible}
      onOk={okHandle}
      onCancel={() => handleUpdateModalVisible()}
    >
      <FormItem
        labelCol={{ span: 5 }}
        wrapperCol={{ span: 15 }}
        label="员工姓名"
      >
        {form.getFieldDecorator("nickname", {
          rules: [
            { required: true, message: "请输入2-20个字的姓名", min: 2, max: 20 }
          ],
          initialValue: values.nickname
        })(<Input placeholder="请输入" />)}
      </FormItem>
      <FormItem
        labelCol={{ span: 5 }}
        wrapperCol={{ span: 15 }}
        label="角色"
      >
        {form.getFieldDecorator("roleId",{initialValue:''+values.roleId})(
                <Select placeholder="请选择" style={{ width: "100%" }}>
                  {roleData.map(role => (
                    <Option key={role.id}>{role.roleName}</Option>
                  ))}
                </Select>
              )}
      </FormItem>
    </Modal>
  );
});

/**
 * 查询表单
 */
const QueryForm = Form.create()(props => {
  const { form,handleQuery,roleData } = props;
  const submitHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      handleQuery(fieldsValue);
    });
  };
  
  return (
      <Row gutter={{ md: 6, lg: 24, xl: 48 }}>
        <Col md={6} sm={24}>
          <FormItem label="员工帐号或姓名">
            {form.getFieldDecorator("keyword")(<Input placeholder="请输入" />)}
          </FormItem>
        </Col>
        <Col md={6} sm={24}>
          <FormItem label="状态">
            {form.getFieldDecorator("status")(
              <Select placeholder="请选择" style={{ width: "100%" }}>
                <Option value="">不限</Option>
                <Option value="0">正常</Option>
                <Option value="1">停用</Option>
              </Select>
            )}
          </FormItem>
        </Col>
        <Col md={6} sm={24}>
          <FormItem label="角色">
            {form.getFieldDecorator("roleId")(
              <Select placeholder="请选择" style={{ width: "100%" }}>
                <Option value="">不限</Option>
                {roleData.map(role => (
                  <Option key={role.id}>{role.roleName}</Option>
                ))}
              </Select>
            )}
          </FormItem>
        </Col>
        <Col md={6} sm={24}>
          <span className={styles.submitButtons}>
            <Button type="primary" onClick={submitHandle} >
              查询
            </Button>
          </span>
        </Col>
      </Row>
  );
});

@connect(({ staff,role, loading }) => ({
  staffData: staff.data,
  allRoleData: role.allRoleData,
  listLoading: loading.models.staff
}))
class StaffView extends PureComponent {
  state = {
    modalVisible: false,
    updateModalVisible: false,
    expandForm: false,
    formValues: {},
    initFormValues: {}
  };

  columns = [
    {
      title: "帐号",
      dataIndex: "username"
    },
    {
      title: "姓名",
      dataIndex: "nickname"
    },
    {
      title: "角色",
      dataIndex: "roleName"
    },
    {
      title: "状态",
      dataIndex: "status",
      render(val) {
        return <Badge status={statusMap[val]} text={status[val]} />;
      },
    },
    {
      title: "创建时间",
      dataIndex: "gmtCreate",
      sorter: true,
      render: val => <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span>,
    },
    {
      title: "操作",
      render: (text, record) => (
        <Fragment>
          <a onClick={() => this.handleUpdateModalVisible(true, record)}>
            编辑
          </a>
          <Divider type="vertical" />
          <a onClick={() => this.handleDeleteModalVisible(record)}>删除</a>
        </Fragment>
      )
    }
  ];

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: "staff/list"
    });
    //加载角色数据
    dispatch({
      type: "role/listAll"
    });
  }

  handleTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      currentPage: pagination.current,
      pageSize: pagination.pageSize,
      ...formValues,
      ...filters
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}-${sorter.order}`;
    }
    console.log(params)
    dispatch({
      type: "staff/list",
      payload: params
    });
  };

  handleQuery = fieldsValue => {
    const { dispatch } = this.props;
    dispatch({
      type: "staff/list",
      payload: fieldsValue
    });
  };

  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag
    });
  };

  handleCreate = formValues => {
    const { dispatch } = this.props;

    dispatch({
      type: "staff/create",
      payload: formValues
    });

    message.success("添加成功");
    this.handleModalVisible();
  };

  handleUpdateModalVisible = (flag, record) => {
    this.setState({
      updateModalVisible: !!flag,
      initFormValues: record || {},
    });
  };

  handleUpdate = fields => {
    const { dispatch } = this.props;
    dispatch({
      type: 'staff/update',
      payload: {
        nickname: fields.nickname,
        roleId: fields.roleId,
        id: fields.id,
      },
    });

    message.success('编辑成功');
    this.handleUpdateModalVisible();
  };

  handleDeleteModalVisible = (record) => {
    Modal.confirm({
      title: '删除员工',
      content: '确定删除该员工吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => this.deleteItem(record.id),
    });
  };

  deleteItem = id => {
    const { dispatch } = this.props;
    dispatch({
      type: 'staff/delete',
      payload: { id },
    });
  };

  render() {
    const { staffData,allRoleData, listLoading } = this.props;
    const {
      modalVisible,
      updateModalVisible,
      initFormValues
    } = this.state;

    const createMethods = {
      handleCreate: this.handleCreate,
      handleModalVisible: this.handleModalVisible
    };
    const updateMethods = {
      handleUpdateModalVisible: this.handleUpdateModalVisible,
      handleUpdate: this.handleUpdate,
    };
    const queryMethods = {
      handleQuery:this.handleQuery,
    }
    return (
      <div>
        <div className={styles.tableList}>
          <div className={styles.tableListForm}>
            <QueryForm {...queryMethods} roleData={allRoleData?allRoleData:[]}/>
          </div>
          <div className={styles.tableListOperator}>
            <Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true)}>新建</Button>
          </div>
          <Table
            rowKey="id"
            loading={listLoading}
            dataSource={staffData.list}
            pagination={staffData.pagination}
            columns={this.columns}
            onChange={this.handleTableChange}
            size="middle"
          />
        </div>
        <CreateForm {...createMethods} modalVisible={modalVisible} roleData={allRoleData?allRoleData:[]}/>
        <UpdateForm {...updateMethods} updateModalVisible={updateModalVisible} values={initFormValues} roleData={allRoleData?allRoleData:[]}/>
      </div>
    );
  }
}

export default StaffView;
